﻿using System;
using System.Web;
using System.Web.UI;

namespace Ue.Infrastructure.UI.SkinnedControls.PageParserFilters
{
    public class GenericPageParserFilter : PageParserFilter
    {
        private string viewBaseType;

        public override void PreprocessDirective(string directiveName, System.Collections.IDictionary attributes)
        {
            base.PreprocessDirective(directiveName, attributes);

            if (directiveName == "control")
            {
                string inherits = (string)attributes["inherits"];
                if (!string.IsNullOrEmpty(inherits)
                    && IsGenericTypeString(inherits))
                {
                    attributes["inherits"] = typeof(GenericUserControl).FullName;
                    this.viewBaseType = inherits;
                }
            }
        }

        public override void ParseComplete(ControlBuilder rootBuilder)
        {
            base.ParseComplete(rootBuilder);

            GenericUserControlBuilder userControlBuilder = rootBuilder as GenericUserControlBuilder;
            if (userControlBuilder != null)
                userControlBuilder.UserControlBaseType = this.viewBaseType;
        }

        public override bool ProcessCodeConstruct(CodeConstructType codeType, string code)
        {
            return base.ProcessCodeConstruct(codeType, code);
        }

        private bool IsGenericTypeString(string typeName)
        {
            //C# and VB generic syntax
            //what about other language
            return typeName.IndexOfAny(new char[] { '<', '(' }) >= 0;
        }

        #region override default methods and properties

        public override bool AllowVirtualReference(string referenceVirtualPath, VirtualReferenceType referenceType)
        {
            return true;
        }

        public override bool AllowServerSideInclude(string includeVirtualPath)
        {
            return true;
        }

        public override bool AllowControl(Type controlType, ControlBuilder builder)
        {
            return true;
        }

        public override bool AllowBaseType(Type baseType)
        {
            return true;
        }

        public override bool AllowCode
        {
            get { return true; }
        }

        public override int NumberOfControlsAllowed
        {
            get { return -1; }
        }

        public override int TotalNumberOfDependenciesAllowed
        {
            get { return -1; }
        }

        public override int NumberOfDirectDependenciesAllowed
        {
            get { return -1; }
        }

        #endregion
    }
}
